package com.dhcc.DRGsHosp.facade.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.inject.Named;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dayatang.domain.EntityRepository;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.QueryChannelService;
import org.dayatang.utils.Page;
import org.openkoala.koala.commons.InvokeResult;
import org.openkoala.security.core.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import com.dhcc.DRGsHosp.application.ClinicGroupApplication;
import com.dhcc.DRGsHosp.application.DepGroupApplication;
import com.dhcc.DRGsHosp.application.DepartmentApplication;
import com.dhcc.DRGsHosp.core.domain.DepGroup;
import com.dhcc.DRGsHosp.core.domain.Department;
import com.dhcc.DRGsHosp.facade.DepartmentFacade;
import com.dhcc.DRGsHosp.facade.DrgsIndexCalFacade;
import com.dhcc.DRGsHosp.facade.dto.DepartmentDTO;
import com.dhcc.DRGsHosp.facade.dto.IndexCalDTO;
import com.dhcc.DRGsHosp.facade.impl.assembler.DepartmentAssembler;
import com.dhcc.DRGsHosp.facade.impl.assembler.IndexCalAssembler;
import com.dhcc.DRGsHosp.infra.util.DrgsIndex;
import com.dhcc.DRGsHosp.infra.util.ExcelUtil;
import com.dhcc.DRGsHosp.infra.util.StringUtils;

@Named("drgsHospFacadeImpl5")
public class DepartmentFacadeImpl implements DepartmentFacade {

	@Autowired
	private DepartmentApplication  application;
	@Autowired
	private DepGroupApplication  depGroupApplication;
	@Autowired
	private ClinicGroupApplication  clinicGroupApplication;
	@Autowired
	private DrgsIndexCalFacade drgsIndexCalFacade;
	
	private QueryChannelService queryChannel;

	private EntityRepository getRepository() {
		EntityRepository repository = null;
		if (repository == null) {
			repository = InstanceFactory.getInstance(
					EntityRepository.class, "repository");
		}
		return repository;
	}
	
    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
	
	public InvokeResult creatDepartment(DepartmentDTO departmentDTO) {
		Department depOld = application.getDepartment(departmentDTO.getDepCode());
		if(null != depOld){
			return InvokeResult.failure("【"+departmentDTO.getDepCode()+"】的科室已经存在");
		}
		departmentDTO.setValidStates("1");//科室状态
		application.creatDepartment(DepartmentAssembler.toEntity(departmentDTO));
		return InvokeResult.success();
	}
	
	public InvokeResult updateDepartment(DepartmentDTO departmentDTO) {
		departmentDTO.setValidStates("1");//科室状态
		application.updateDepartment(DepartmentAssembler.toEntity(departmentDTO));
		return InvokeResult.success();
	}
	
	public InvokeResult removeDepartment(String depCode) {
		application.removeDepartment(application.getDepartment(depCode));
		return InvokeResult.success();
	}
	
	public InvokeResult removeDepartments(String[] depCodes) {
		Set<Department> departments= new HashSet<Department>();
		StringBuilder depStr = new StringBuilder() ;
		for (String depCode : depCodes) {
			Department dep = application.getDepartment(depCode);
			if(hasCliSpec(depCode)){
				depStr.append(dep.getDepName() + ",") ;
			} else {
				departments.add(dep);
			}
		}
		application.removeDepartments(departments);
		if(StringUtils.hasLength(depStr.toString())){
			String depString = depStr.substring(0, depStr.lastIndexOf(",")) ;
			return InvokeResult.failure("请取消  "+depString+" 科室所选临床专业");
		}
		return InvokeResult.success();
	}
	
	public List<DepartmentDTO> findAllDepartment() {
		return DepartmentAssembler.toDTOs(application.findAllDepartment());
	}
	
	public Page<DepartmentDTO> pageQueryDepartment(DepartmentDTO queryVo, int currentPage, int pageSize) {
		List<Object> conditionVals = new ArrayList<Object>();
		StringBuilder jpql = new StringBuilder("select new Department(_department.depCode,"
				+ "_department.parDepGroupCode,_department.depName,_department.depHisCode,"
				+ "_department.depHis,_department.depTelephone,_department.depLeader,"
				+ "_department.validStates,_department.depOrder,_department.depBedCnt,"
				+ "_department.depDoctorCnt,_department.isOpeDep,_department.parHospCode,_department.depType ) "
				+ "from Department _department where 1=1 ");
	   	if (queryVo.getDepCode() != null && !"".equals(queryVo.getDepCode())) {
	   		jpql.append(" and _department.depCode like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepCode()));
	   	}		
	   	if (queryVo.getParDepGroupCode() != null && !"".equals(queryVo.getParDepGroupCode())) {
	   		jpql.append(" and _department.parDepGroupCode =?");
	   		conditionVals.add(queryVo.getParDepGroupCode());
	   	}
	   	if (queryVo.getDepName() != null && !"".equals(queryVo.getDepName())) {
	   		jpql.append(" and _department.depName like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepName()));
	   	}		
	   	if (queryVo.getDepTelephone() != null && !"".equals(queryVo.getDepTelephone())) {
	   		jpql.append(" and _department.depTelephone like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepTelephone()));
	   	}		
	   	if (queryVo.getDepLeader() != null && !"".equals(queryVo.getDepLeader())) {
	   		jpql.append(" and _department.depLeader like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepLeader()));
	   	}
	   	if (queryVo.getValidStates() != null && !"".equals(queryVo.getValidStates())) {
	   		jpql.append(" and _department.validStates like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getValidStates()));
	   	}		
	   	if (queryVo.getDepOrder() != null && !"".equals(queryVo.getDepOrder())) {
	   		jpql.append(" and _department.depOrder like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDepOrder()));
	   	}
	   	if (queryVo.getDepBedCnt() != null) {
	   		jpql.append(" and _department.depBedCnt=?");
	   		conditionVals.add(queryVo.getDepBedCnt());
	   	}
	   	if (queryVo.getIsOpeDep() != null) {
	   		jpql.append(" and _department.isOpeDep=?");
	   		conditionVals.add(queryVo.getIsOpeDep());
	   	}
	   	if (queryVo.getDepDoctorCnt() != null) {
	   		jpql.append(" and _department.depDoctorCnt=?");
	   		conditionVals.add(queryVo.getDepDoctorCnt());
	   	}
	   	if (queryVo.getParHospCode() != null&& !"".equals(queryVo.getParHospCode())) {
	   		jpql.append(" and _department.parHospCode=?");
	   		conditionVals.add(queryVo.getParHospCode());
	   	}
	   	jpql.append(" order by  _department.depOrder ");
        Page<Department> pages = getQueryChannelService()
		   .createJpqlQuery(jpql.toString())
		   .setParameters(conditionVals)
		   .setPage(currentPage, pageSize)
		   .pagedList();
        List<Department> listDep = new ArrayList<Department>() ;
        listDep = pages.getData() ;
        List<Map<String,Object>> allHospCodeMap=findAllHosp();
        Map<String,String> hospCodeMap=new HashMap<String,String>();
        for(Map<String,Object> map:allHospCodeMap){
        	hospCodeMap.put(map.get("HOSP_CODE").toString(), map.get("HOSP_NAME").toString());
        }
        Map<String,Object> drgCountInDep = findDRGCount() ;
        for(Department dep : listDep) {
        	if( dep!= null){
        		String depCode = dep.getDepCode() != null ? dep.getDepCode() : "" ;
        		if(drgCountInDep.containsKey(depCode)){
        			dep.setCountDRG((Integer)drgCountInDep.get(depCode));
        		} else {
        			dep.setCountDRG(0);
        		}
        		dep.setHospDesc(dep.getParHospCode()==null?"":hospCodeMap.get(dep.getParHospCode())==null?"":hospCodeMap.get(dep.getParHospCode()));
        	}
        }
        return new Page<DepartmentDTO>(pages.getStart(), pages.getResultCount(),pageSize, DepartmentAssembler.toDTOs(pages.getData()));
	}
	
	@Override
	public DepartmentDTO getCurrentUserDepartment(String account){
		User user = User.getByUserAccount(account);
		String depCode = "";
		if(user.getDepartment() != null){
			depCode = user.getDepartment().getDepCode();
			Department dep = Department.getBy(depCode);
			return DepartmentAssembler.toDTO(dep);
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DepartmentFacade#findAllDep(com.dhcc.DRGsHosp.facade.dto.DepartmentDTO)
	 */
	@Override
	public Object findAllDep(DepartmentDTO dto) {
		// TODO Auto-generated method stub
		return application.findAllDepartment(DepartmentAssembler.toEntity(dto));
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DepartmentFacade#isOrderExist(java.lang.String)
	 */
	@Override
	public Boolean isOrderExist(String order,String code) {
		// TODO Auto-generated method stub
		return application.isOrderExist(order,code);
	}

	@Override
	public List<Object[]> queryHoptalCode() {
		// TODO Auto-generated method stub
		StringBuilder jpql = new StringBuilder("select hosp.hosp_code,hosp.hosp_name from DRGs.t_hospital hosp  where  1=1 ");		
		List<Object[]> sqlList = getRepository().createSqlQuery(jpql.toString()).list();
		return sqlList;
	}

	@Override
	public List<String> getNewAddDepNames() {
		StringBuilder jpql = new StringBuilder("select d.dep_name from DRGs.t_department d  where  d.pardepgroup_code = 'XZKSKSZ' ");		
		List<String> sqlList = getRepository().createSqlQuery(jpql.toString()).list();
		return sqlList;
	}
	
	@Override
	public Boolean saveSelCliSpec(String depCode, String verCode ,String[] drgCodes_spec) {
		// TODO Auto-generated method stub
		boolean flag = true  ;
		Map<String,Object> condition0 = new HashMap<>() ;
		condition0.put("depCode", depCode) ;
		condition0.put("verCode", verCode) ;
		if( drgCodes_spec == null){//删除科室下 该版本的所有ADRG
			String sql = " delete from drgs.t_departmentdrg dd where dd.pardep_code = :depCode and dd.version = :verCode " ;
			 int count = application.excuteUpdate(sql, condition0) ;
			 if(count <= 0 ){
				 flag = false ;
			 }
		} else { //  根据 条件 增删
			String drgCodesString = com.dhcc.DRGsHosp.infra.util.StringUtils.convertArrayToQuoteString( drgCodes_spec ) ;
			String sqlSel = " select 1 from ( " +
							" select t.parspec_code||'#'||t.pardrg_code  drgcode \n" +
							 " from drgs.t_departmentdrg t where t.version = :verCode and  t.pardep_code = :depCode) a   \n" +
							 " where a.drgcode not in ("+drgCodesString+") " ;
			List<Object> listResult = getRepository().createSqlQuery(sqlSel).setParameters(condition0).list() ;
			if(listResult.size() > 0 ){
				String sqlDel = "delete from ( " +
						" select t.parspec_code||'#'||t.pardrg_code  drgcode,t.version  \n" +
						 " from drgs.t_departmentdrg t  where t.version = :verCode and  t.pardep_code = :depCode) a \n" +
						 " where a.drgcode not in ("+drgCodesString+") " ;
				int count = application.excuteUpdate(sqlDel, condition0 ) ;
				flag = count <= 0 ? false : true ;
			}  
			
			for(String drgCode_spec : drgCodes_spec) {
				String[] drgCodeSpec_array =  drgCode_spec.split("#") ;
				if(drgCodeSpec_array.length != 2){
					return false ; 
				}
				String specCode = drgCodeSpec_array[0] != null ? drgCodeSpec_array[0] : "" ;
				String drgCode = drgCodeSpec_array[1] != null ? drgCodeSpec_array[1] : "" ;
				Map<String,Object> condition = new HashMap<>() ;
				condition.put("specCode",specCode) ;
				condition.put("verCode", verCode) ;
				condition.put("drgCode", drgCode) ;
				condition.put("depCode", depCode) ;
				String sql = " select 1 from drgs.t_departmentdrg t where t.pardep_code = :depCode and t.parspec_code = :specCode  " +
							 " and t.pardrg_code = :drgCode and t.version = :verCode " ;
				List<Object> list = getRepository().createSqlQuery(sql).setParameters(condition).list() ;
				 if(list.size() == 0){ // 增加
					 condition.put("id",UUID.randomUUID().toString()) ;
					 String sqlInsert = " insert into drgs.t_departmentdrg t (t.id,t.pardep_code,t.parspec_code,t.pardrg_code,t.version)  " +
							 		" values (:id,:depCode , :specCode , :drgCode , :verCode) " ;
					 int count = application.excuteUpdate(sqlInsert, condition) ;
					 if(count <= 0){
						 flag = false ;
					 }
				 } 
			}
		}
		return flag;
	}


	@Override
	public List<Map<String, Object>> findSpecBydepCode(String depCode) {
		// TODO Auto-generated method stub
		List<Map<String, Object>> resultList = new ArrayList<>() ;
		/**
		 * DRG版本 列表
		 */
//		List<Object> listVersion = new ArrayList<Object>() ;
		Map<String, Object> condition = new HashMap<>();
		depCode = depCode != null ? depCode : "" ;
		condition.put("depCode", depCode ) ;
		// 先查询某个临床专业下选了几个版本
		String sqlVersion = "  select distinct dd.version , dv.ver_desc  \n" +
								" from drgs.t_departmentdrg dd \n" +
								" left join drgs.t_drgversion dv on dv.ver_code = dd.version \n" +
								" where dd.pardep_code = :depCode "  ;
		List<Map<String,Object>> versionList = application.executeQueryForList(sqlVersion, condition)  ;
		if( versionList != null && versionList.size() >0 ){
			for(Map<String,Object> map : versionList){
				Map<String,Object> resultMap = new HashMap<>() ;
				String version = map.get("VERSION") !=null ? map.get("VERSION").toString() : ""  ;
				String verDesc = map.get("VER_DESC") !=null ? map.get("VER_DESC").toString() : ""  ;
				// 查询 临床专业下 某版本的 DRG
				String sql = "  select dd.parspec_code,cs.spec_desc,drg.drg_code,drg.drg_desc,mdc.mdc_code,mdc.mdc_desc,adrg.adrg_code,adrg.adrg_desc from drgs.t_departmentdrg dd \n" +
								" left join drgs.t_clispec cs on cs.spec_code = dd.parspec_code  \n" + 
								" left join drgs.t_drgs drg on drg.drg_code = dd.pardrg_code and drg.ver_code = dd.version \n" +
								" left join drgs.t_adrg adrg on adrg.adrg_code = drg.adrg_code and adrg.ver_code = drg.ver_code  \n" +
								" left join drgs.t_mdcgroup mdc on adrg.mdc_code = mdc.mdc_code and adrg.ver_code = mdc.ver_code  \n" +
								" where dd.version = :version and dd.pardep_code = :depCode " ;
				condition.put("version", version) ;
				List<Map<String,Object>> drgList = application.executeQueryForList(sql, condition) ;
				resultMap.put("version", version) ;
				resultMap.put("verDesc", verDesc) ;
				resultMap.put("drgList", drgList) ;
				resultList.add(resultMap) ;
			}
		}
		return resultList;
	}

	@Override
	public Map<String, Object> findDRGCount() {
		// TODO Auto-generated method stub
		Map<String,Object> map = new HashMap<>() ;
		String sql = "select dd.pardep_code ,count(dd.pardrg_code) count from drgs.t_departmentdrg dd group by dd.pardep_code" ;
		List<Object[]> list = getRepository().createSqlQuery(sql).list() ;
		if(list != null && list.size() >0){
			for(Object[] objArr : list){
				String depCode = (String) (objArr[0] != null ? objArr[0] : "") ;
				String countADRGStr =  (objArr[1] != null ? objArr[1].toString() : "") ;
				Integer countADRG = Integer.parseInt(countADRGStr) ;
				map.put(depCode, countADRG ) ;
			}
		}
		return map;
	}

	@Override
	public boolean hasCliSpec(String depCode) {
		// TODO Auto-generated method stub
		String sql = "select count(da.pardrg_code) from drgs.t_departmentdrg da  where da.pardep_code = :depCode" ;
		String countStr = getRepository().createSqlQuery(sql).addParameter("depCode", depCode).list().get(0).toString() ;
		Integer count =  countStr!= null ? Integer.parseInt(countStr) : 0;
		if(count > 0) {
			return true;
		} 
		return false ;
	}

	@Override
	public InvokeResult findDepDRGs(String depCode) {
		List<Object[]> list = application.findDepDRGs(depCode);
		List<Map<String, Object>> resultList = new LinkedList<>();
		for(Object[] objs: list){
			Map<String, Object> map = new HashMap<>();
			map.put("ccode", objs[0]);
			map.put("ddesc", objs[1]);
			resultList.add(map);
		}
		return InvokeResult.success(resultList);
	}

	@Override
	public DepartmentDTO findDepartmentByDepCode(String depCode) {
		// TODO Auto-generated method stub
		Department dep = application.findDepartmentByDepCode(depCode) ;
		return DepartmentAssembler.toDTO(dep);
	}

	@Override
	public InvokeResult findDoctorInDep(String depCode) {
		String clinicNames=clinicGroupApplication.findClinicGroupsByDepCode(depCode);
		return InvokeResult.success(clinicNames);
	}
	
	@Override
	public List<Map<String, Object>> findAllDepRelatedInfo() {
		StringBuffer strb = new StringBuffer() ;
		strb.append(" select dep.dep_code depcode,dep.dep_name depname,depgroup.depgroup_code depgroupcode, \n ") ;
		strb.append(" depgroup.depgroup_desc depgroupdesc,ward.ward_code wardcode,ward.ward_desc warddesc \n ") ;
		strb.append(" from drgs.t_department dep \n ") ;
		strb.append(" left join drgs.t_depgroup depgroup on dep.pardepgroup_code  = depgroup.depgroup_code \n ") ;
		strb.append(" left join drgs.t_ward ward on dep.dep_code = ward.pardep_code \n ") ;
		return application.executeQueryForList(strb.toString(),new HashMap<String,Object>()) ;
	}
/**
 * 
 *  @Description：根据条件获取科室信息
 *  @Author lhj 
 *  @see com.dhcc.DRGsHosp.facade.DepartmentFacade#findAllDepByHospCode(com.dhcc.DRGsHosp.facade.dto.IndexCalDTO)
 */
	@Override
	public Object findAllDepByHospCode(IndexCalDTO dto) {
		return application.findAllDepByHospCode(IndexCalAssembler.toEntity(dto));
	}

	@Override
	public List<Map<String, Object>> findAllHosp() {
		// TODO Auto-generated method stub
		return application.findAllHosp();
	}
	
	/**  
	 *  @Description：更新科室所属的院区code
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.DepartmentFacade#updateBaseInfo(java.lang.String, java.lang.String)  
	 */
	@Override
	public void updateBaseInfo(String depCode, String hospCode) {
		application.updateBaseInfo(depCode, hospCode);
	}
	
	/**
	 * 
	 * @Description: 科室设置中一键同步
	 * @author shaozhiyuan 
	 * @date 2018年3月13日  
	 * @version V3.1.0
	 */
	@Override
	public InvokeResult synchroDepAndHosp(String[] depCodes) {
		for (String depCode : depCodes) {
			String strb = "";
			Map<String,Object> condition0 = new HashMap<>() ;
			strb=" update drgs.mr_baseinfo ba  set ba.P00010001=( select d.parhosp_code  from  drgs.t_department d left join drgs.mr_ipinfo i on i.P00300001=d.dep_code where ba.pmainindex=i.pmainindex) ";
			strb +="where exists ( select 1 from  drgs.mr_ipinfo ip  where ba.pmainindex=ip.pmainindex and ip.P00300001 ='"+depCode.trim()+"') ";
			int countA = application.excuteUpdate(strb, condition0 ) ;
		}
		String strc = "";
		Map<String,Object> condition1 = new HashMap<>() ;
		strc=" update drgs.mr_baseinfo ba set ba.P00010000=( select h.hosp_name from drgs.t_hospinfo h where h.hosp_code=ba.p00010001) ";
		int countB = application.excuteUpdate(strc, condition1 ) ;
		return InvokeResult.success();
	}
	@Override
	public List<String> getDepNotification() {
		StringBuilder jpql = new StringBuilder("SELECT DEP_NAME FROM DRGS.T_DEPARTMENT D  WHERE D.DEP_TYPE='E' AND D.PARDEPGROUP_CODE IS NULL");		
		List<String> sqlList = getRepository().createSqlQuery(jpql.toString()).list();
		return sqlList;
	}
	@Override
	public List<String> getHospNotification() {
		StringBuilder jpql = new StringBuilder("SELECT DEP_NAME FROM DRGS.T_DEPARTMENT D  WHERE D.DEP_TYPE='E' AND  PARHOSP_CODE IS NULL ");		
		List<String> sqlList = getRepository().createSqlQuery(jpql.toString()).list();
		return sqlList;
	}
	@Override
	public InvokeResult departmentImport(String filePath) {
		Double order = application.findOrderMax() ;
		StringBuffer message = new StringBuffer();//返回前台的信息
		//查询科室组数据
		List<DepGroup> depGroupList = depGroupApplication.findAllDepGroup();
		if(depGroupList.isEmpty()){
			message.append("尚未导入科室组数据，请先导入科室组数据!");
			return InvokeResult.success(message) ;
		}
		List<String> depGroupCodeList = new ArrayList<>();
		for (int i=0 ; i < depGroupList.size() ; i++) {
			depGroupCodeList.add(depGroupList.get(i).getDepGroupCode()) ;
		}
		String extension = filePath.substring(filePath.lastIndexOf("."));// 扩展名
		Workbook workbook = null;
		Sheet sheet = null;
		if (extension.equals(".xls")) {
			try {
				workbook = new HSSFWorkbook(new FileInputStream(
						filePath));
				sheet = (HSSFSheet) workbook.getSheetAt(0);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else if (extension.equals(".xlsx")) {
			try {
				workbook = new XSSFWorkbook(new FileInputStream(
						filePath));
				sheet = (XSSFSheet) workbook.getSheetAt(0);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.err.println("上传的文件不是有效的excel文件！");
		}
		int rowNum=sheet.getLastRowNum();//行数
		int errorRow = 0;
		Row row = null ;
		// 存放文件的表头位置
		Map<String,Object> titlemap = new HashMap<>();
		// 标题行
		Row headrow = sheet.getRow(0);
		int headCount = headrow.getLastCellNum();
		Cell cell=null;
		for (int i = 0; i < headCount; i++) {
			cell = headrow.getCell((short) i);
			titlemap.put(cell.getStringCellValue(), i);
		}
		int rowCnt=0;
		try {
			message.setLength(0);
			for(int i = 1 ; i <= rowNum ; i++) {
				errorRow = i;
				row=sheet.getRow(i);
				// 该行为空时解析下一行
				if(null == row) {
					continue ;
				}
				Department dep=new Department();
				cell = row.getCell((int) (titlemap.get("科室代码") != null ? titlemap.get("科室代码"):1000));
				String depCode=ExcelUtil.getCellValue(cell);
				if( null == depCode) {
					message.append("第" + (i) +"行数据没有科室代码，请检查。<br>"); 
					continue ;
				}
				dep.setDepCode(depCode);
				cell = row.getCell((int) (titlemap.get("科室名称") != null ? titlemap.get("科室名称"):1000));
				String depName=ExcelUtil.getCellValue(cell);
				if( null == depName) {
					message.append("第" + (i) +"行数据没有科室描述，请检查。<br>"); 
					continue ;
				}
				dep.setDepName(depName);
				
				cell = row.getCell((int) (titlemap.get("所属科室组代码") != null ? titlemap.get("所属科室组代码"):1000));
				String depGroupCode=ExcelUtil.getCellValue(cell);
				if(depGroupCode!=null&&!depGroupCodeList.contains(depGroupCode)) {
					message.append("第" + (i) +"行科室组代码"+depGroupCode+"不存在，请检查。<br> ");
					continue;
				}
				dep.setParDepGroupCode(depGroupCode);
				
				cell = row.getCell((int) (titlemap.get("院区代码") != null ? titlemap.get("院区代码"):1000));
				String hospCode=ExcelUtil.getCellValue(cell);
				if( null == hospCode) {
					message.append("第" + (i) +"行数据没有院区代码，请检查。<br>"); 
					continue ;
				}
				dep.setParHospCode(hospCode);
				
				cell = row.getCell((int) (titlemap.get("科室类型") != null ? titlemap.get("科室类型"):1000));
				dep.setDepType("S".equals(ExcelUtil.getCellValue(cell))?"S":"E");
				cell = row.getCell((int) (titlemap.get("科室电话") != null ? titlemap.get("科室电话"):1000));
				dep.setDepTelephone(ExcelUtil.getCellValue(cell));
				cell = row.getCell((int) (titlemap.get("科室负责人") != null ? titlemap.get("科室负责人"):1000));
				dep.setDepLeader(ExcelUtil.getCellValue(cell));
				
				cell = row.getCell((int) (titlemap.get("有效状态") != null ? titlemap.get("有效状态"):1000));
				String validStates=ExcelUtil.getCellValue(cell);
				if( null == validStates) {
					message.append("第" + (i) +"行数据没有有效状态，请检查。<br>"); 
					continue ;
				}
				dep.setValidStates(validStates);
				
				cell = row.getCell((int) (titlemap.get("显示顺序") != null ? titlemap.get("显示顺序"):1000));
				String depOrder=ExcelUtil.getCellValue(cell);
				if(depOrder == null){
					dep.setDepOrder(++order);
				} else if(depOrder!=null&&!depOrder.matches("^\\d+$")) {
					message.append("第"+(i)+"行 数据显示顺序不是合法数字，请检查。 </br>");
					continue ;
				}
				else if(depOrder!=null&&application.isOrderExist(depOrder, depCode)){
					message.append("第" + (i) +"行数据显示顺序已经存在，请检查。<br>"); 
					continue ;
				}
				else{
					double orderTemp = depOrder==null?null:Double.valueOf(depOrder);
					if(order<orderTemp) {
						order = orderTemp;
					}
					dep.setDepOrder(orderTemp);
				}
				cell = row.getCell((int) (titlemap.get("HIS科室名称") != null ? titlemap.get("HIS科室名称"):1000));
				dep.setDepHis(ExcelUtil.getCellValue(cell));
				cell = row.getCell((int) (titlemap.get("HIS科室代码") != null ? titlemap.get("HIS科室代码"):1000));
				dep.setDepHisCode(ExcelUtil.getCellValue(cell));
				cell = row.getCell((int) (titlemap.get("科室床位数") != null ? titlemap.get("科室床位数"):1000));
				String bedCnt=ExcelUtil.getCellValue(cell);
				dep.setDepBedCnt(bedCnt==null?null:Double.valueOf(bedCnt));
				cell = row.getCell((int) (titlemap.get("科室医生数") != null ? titlemap.get("科室医生数"):1000));
				String doctorCnt=ExcelUtil.getCellValue(cell);
				dep.setDepDoctorCnt(doctorCnt==null?null:Double.valueOf(doctorCnt));
				cell = row.getCell((int) (titlemap.get("是否为手术科室") != null ? titlemap.get("是否为手术科室"):1000));
				String isOperDep=ExcelUtil.getCellValue(cell);
				dep.setIsOpeDep(isOperDep==null?null:Double.valueOf(isOperDep));
				cell = row.getCell((int) (titlemap.get("标准科室代码") != null ? titlemap.get("标准科室代码"):1000));
				dep.setSpecCode(ExcelUtil.getCellValue(cell));
				application.creatDepartment(dep);
				rowCnt++;
			}
			message.append("导入完成，共导入"+rowCnt+"条数据!");
		} catch (Exception e) {
			e.printStackTrace();
			message.append("第" + (errorRow) +"行数据导入时报错，导入终止。<br>"); 
			return InvokeResult.failure(message.toString());
		} finally {
			ExcelUtil.deleteFile(filePath) ;
		}
		return InvokeResult.success(message) ;
	}

	@Override
	public List<Map<String, Object>> findDepartmentDRGs(IndexCalDTO dto) {
		String sql = " select dd.pardrg_code drgcode,dd.pardep_code depcode from DRGs.t_Departmentdrg dd where dd.version = :version " ;
		// 获取系统分组版本
		Map<String, Object> condition = new HashMap<>() ;
		dto.setDateFrom(DrgsIndex.formateDateFrom(dto.getDateFrom()));
		dto.setDateTo(DrgsIndex.formateDateTo(dto.getDateTo()));
		String version = drgsIndexCalFacade.getVerCode(dto.getDateFrom(), dto.getDateTo()) ;
		condition.put("version", version) ;
		return application.executeQueryForList(sql, condition) ;
	}
}
